<template>
	<view class="image-uploader">
		<view class="image-list">
			<view v-for="(image, index) in images" :key="index" class="image-item">
				<image :src="image.url" class="preview-image" mode="aspectFill" />
				<view class="delete-btn" @click="removeImage(index)">
					<uni-icons type="closeempty" size="18" color="#fff" />
				</view>
			</view>
			<view v-if="images.length < maxCount" class="upload-btn" @click="chooseImage">
				<uni-icons type="plusempty" size="28" color="#ccc" />
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, defineProps, defineEmits } from 'vue';

	// Props to receive data from parent
	defineProps({
		maxCount: {
			type: Number,
			default: 5, // Maximum number of images
		},
		uploadUrl: {
			type: String,
			required: true, // Upload API endpoint
		},
	});

	// Emits to send data back to the parent component
	const emit = defineEmits(['update:images']);

	// Manage selected images
	const images = ref<{ url : string; file : any }[]>([]);

	// Choose and upload image
	const chooseImage = () => {
		uni.chooseImage({
			count: maxCount - images.value.length, // Limit remaining images
			success: (res) => {
				res.tempFilePaths.forEach(async (filePath, index) => {
					const file = res.tempFiles[index];
					const uploadResult = await uploadImage(filePath, file);
					if (uploadResult) {
						images.value.push(uploadResult);
						emit('update:images', images.value); // Notify parent about the change
					}
				});
			},
		});
	};

	// Upload image to the server
	const uploadImage = (filePath : string, file : any) => {
		return new Promise<{ url : string; file : any } | null>((resolve, reject) => {
			uni.uploadFile({
				url: uploadUrl, // Upload API endpoint
				filePath,
				name: 'file', // Field name for the file
				formData: {
					fileName: file.name, // Optional, pass file metadata if needed
				},
				success: (uploadFileRes) => {
					const response = JSON.parse(uploadFileRes.data);
					if (response.code === 200) {
						resolve({
							url: response.data.url, // URL of the uploaded image
							file,
						});
					} else {
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none',
						});
						resolve(null);
					}
				},
				fail: () => {
					uni.showToast({
						title: '上传失败，请检查网络',
						icon: 'none',
					});
					resolve(null);
				},
			});
		});
	};

	// Remove selected image
	const removeImage = (index : number) => {
		images.value.splice(index, 1);
		emit('update:images', images.value); // Notify parent about the change
	};
</script>

<style scoped>
	.image-uploader {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.image-item {
		position: relative;
		width: 200rpx;
		height: 200rpx;
	}

	.preview-image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
		object-fit: cover;
	}

	.delete-btn {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		padding: 6rpx;
		cursor: pointer;
	}

	.upload-btn {
		width: 200rpx;
		height: 200rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		border: 1rpx dashed #ccc;
		cursor: pointer;
	}
</style>